import { request } from "../../utils/request";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [], //左侧菜单数据
    rightContent: [], //右侧商品数据
    currentIndex: 0, //当前选中的菜单索引
    scrollTop: 0 //右侧商品数据的滚动条位置
  },

  //所有商品分类数据
  categoryProducts: [],

  /**
   * 切换菜单事件
   */
  changeMenu(event) {
    //获取当前点击的索引
    let index = event.currentTarget.dataset.index
    //获取全局app对象
    let app = getApp()
    //将全局索引设置为用户点击的索引
    app.globalData.menuIndex = index
    //获取索引所对应的右侧内容数据
    let productData = this.categoryProducts[index].categoryLevel2List;
    this.setData({
      currentIndex: index,
      rightContent: productData,
      scrollTop: 0
    })
  },

  /**
   * 加载分类及分类商品数据
   */
  async loadCategoryProduct() {
    const res = await request({ url: "/category/listCategoryProduct", method: "GET" })
    this.categoryProducts = res.data.data;
    //获取当前一级菜单数据并装填到左边菜单数组中
    let menuData = this.categoryProducts.map(categoryProduct => {
      return categoryProduct.name
    })
    //获取全局app对象
    let app = getApp()
    //获取全局菜单索引
    let index = app.globalData.menuIndex
    let productData = this.categoryProducts[index].categoryLevel2List;
    this.setData({
      currentIndex: index,
      leftMenuList: menuData,
      rightContent: productData
    })
  },

  /**
   * 跳转分类
   */
  jumpCategory() {
    //获取全局app对象
    const app = getApp()
    //获取全局菜单索引
    const index = app.globalData.menuIndex
    //获取索引所对应的右侧内容数据
    const productData = this.categoryProducts[index].categoryLevel2List;
    this.setData({
      currentIndex: index,
      rightContent: productData,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //如果页面数据已经被加载过，则只是设置菜单和对应的数据
    if (this.categoryProducts != undefined && this.categoryProducts.length > 0) {
      this.jumpCategory();
      return;
    }
    //如果页面数据是首次加载，则发送请求进行设置
    this.loadCategoryProduct();
  }
})